use std::env;
use std::fs;
use std::path::Path;

fn main() {
    let args: Vec<String> = env::args().collect();
    
    if args.len() < 3 {
        eprintln!("用法: {} <输入文件> <输出文件>", args[0]);
        std::process::exit(1);
    }
    
    let input_file = &args[1];
    let output_file = &args[2];
    
    match process_yaml_file(input_file, output_file) {
        Ok(_) => {
            println!("✓ 处理完成");
            println!("✓ 输出文件: {}", output_file);
        }
        Err(e) => {
            eprintln!("✗ 错误: {}", e);
            std::process::exit(1);
        }
    }
}

fn process_yaml_file(input_path: &str, output_path: &str) -> Result<(), Box<dyn std::error::Error>> {
    // 读取输入文件
    let content = fs::read_to_string(input_path)?;
    
    // 处理内容
    let result = process_content(&content, input_path)?;
    
    // 写入输出文件
    fs::write(output_path, result)?;
    
    Ok(())
}

fn process_content(content: &str, input_path: &str) -> Result<String, Box<dyn std::error::Error>> {
    let lines: Vec<&str> = content.lines().collect();
    let mut result = Vec::new();
    
    for line in lines {
        result.push(line.to_string());
        
        // 查找包含 conf_source 的行
        if line.trim_start().starts_with("conf_source:") {
            // 提取文件路径
            let file_path = line.trim_start()
                .strip_prefix("conf_source:")
                .unwrap()
                .trim()
                .trim_matches('"')
                .trim_matches('\'');
            
            // 读取外部文件
            let external_content = read_external_file(file_path, input_path)?;
            
            // 计算缩进
            let indent = " ".repeat(line.len() - line.trim_start().len());
            
            // 插入 conf_para
            result.push(format!("{}conf_para: |", indent));
            for ext_line in external_content.lines() {
                result.push(format!("{}  {}", indent, ext_line));
            }
        }
    }
    
    Ok(result.join("\n"))
}

fn read_external_file(file_path: &str, input_path: &str) -> Result<String, Box<dyn std::error::Error>> {
    let full_path = if Path::new(file_path).is_absolute() {
        file_path.to_string()
    } else {
        // 相对路径，基于输入文件的目录
        let input_dir = Path::new(input_path).parent().unwrap_or(Path::new("."));
        input_dir.join(file_path).to_string_lossy().to_string()
    };
    
    fs::read_to_string(&full_path)
        .map_err(|e| format!("无法读取文件 {}: {}", full_path, e).into())
}